#include "qworldscene.h"

#include <QGraphicsEllipseItem>

#include "qlifegraphicsitem.h"
#include "qlife.h"


QWorldScene::QWorldScene ( int width, int height, QObject *parent ) : QGraphicsScene ( parent )
{
	lines = false;
	circles = false;

	dimRect = addRect ( QRectF ( 0, 0, width, height ) );
}

QWorldScene::~QWorldScene()
{
	reset();
}

void QWorldScene::setDimension ( int width, int height )
{
	removeItem ( dimRect );
	dimRect = addRect ( QRectF ( 0, 0, width, height ) );
	update();
}

void QWorldScene::drawLines ( bool lines )
{
	QLifeGraphicsItem* current;
	QList<QLifeGraphicsItem*> list = lifeMap.values();

	for ( int i = 0; i < list.size(); ++i )
	{
		current = list.at ( i );
		current -> setDrawDestination ( lines );
	}

	this -> lines = lines;
}

void QWorldScene::drawCircles ( bool circles )
{
	QLifeGraphicsItem* current;
	QList<QLifeGraphicsItem*> list = lifeMap.values();

	for ( int i = 0; i < list.size(); ++i )
	{
		current = list.at ( i );
		current -> setDrawViewDistance ( circles );
	}

	this -> circles = circles;
}

void QWorldScene::addLife ( QLife* life, QLifeGraphicsItem* item )
{
	// general settings
	item -> setDrawDestination ( lines );
	item -> setDrawViewDistance ( circles );

	addItem ( item );
	item -> setData ( 0, life -> getName() );
	lifeMap.insert ( life -> getId(), item );
}

QList<QGraphicsItem*> QWorldScene::getIntersectingItems ( long id, float viewDistance )
{
	QLifeGraphicsItem* currentItem = lifeMap.value ( id );
	viewAngle -> setRect ( QRectF ( currentItem -> x(), currentItem -> y(), viewDistance, viewDistance ) );

	return viewAngle -> collidingItems();
}

void QWorldScene::reset()
{
	QLifeGraphicsItem* current;
	QList<QLifeGraphicsItem*> list = lifeMap.values();

	for ( int i = 0; i < list.size(); ++i )
	{
		current = list.at ( i );
		removeItem ( current );
	}

	lifeMap.clear();
}

void QWorldScene::removeLife ( long id )
{
	removeItem ( lifeMap.value ( id ) );
	lifeMap.remove ( id );
}
